package com.djf.getchatgptreq.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Service;
import okhttp3.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;

@Service
public class GptService {

    public String getGptService(String code) throws IOException {
        String apiKey = "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";
        String apiUrl = "https://api.openai.com/v1/chat/completions";  // ChatGPT API 的 URL
        String prompt = "Please generate a short comment for the following function:\\n";

        // 创建代理对象
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 21002));

        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .proxy(proxy)
                .build();

        // 创建请求体
        MediaType mediaType = MediaType.parse("application/json");
        String requestBody = "{" +
                "\"model\" : \"gpt-3.5-turbo\"," +
                "\"messages\":[" +
                    "{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}, " +
                    "{\"role\": \"user\", \"content\": \"" + prompt + code + "\"}" +
                "]}";
        RequestBody body = RequestBody.create(requestBody, mediaType);

        // 创建请求对象
        Request request = new Request.Builder()
                .url(apiUrl)
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();

        // 发送请求
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String responseBody = null;
        try {
            responseBody = response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭响应
            response.close();
        }
        JSONObject jsonObject = JSONUtil.parseObj(responseBody);
        JSONArray choices = jsonObject.getJSONArray("choices");
        JSONObject result = choices.get(0, JSONObject.class, Boolean.TRUE);
        JSONObject message = result.getJSONObject("message");

        return message.getStr("content");
    }

    private static String parseGeneratedCode(String jsonResponse) {
        // 解析API响应，提取生成的代码
        // 在这里根据API响应的格式进行解析，并返回生成的代码字符串
        System.out.println("======================");
        System.out.println(jsonResponse);
        return "";
    }
}
